//
//  StringSolution.hpp
//  labuladong
//
//  Created by 刘振舟 on 2024/3/18.
//

#ifndef StringSolution_hpp
#define StringSolution_hpp

#include <stdio.h>
#include <string>
#include <deque>

using namespace std;
 
class StringSolution {
    
public:
    string& trim(string &s) {
        if (s.empty()) {
            return s;
        }
        
        s.erase(0, s.find_first_not_of(" "));
        s.erase(s.find_last_not_of(" ") + 1);
        return s;
    }

    string reverseWords(string s) {
        trim(s);
        deque<string> words;
        string word;
        for (char ch : s) {
            if (word.size() && ch == ' ') {
                words.push_front(move(word));
                word = "";
            } else if (ch != ' ') {
                word.push_back(ch);
            }
        }
        words.push_front(move(word));
        
        string result;
        while (!words.empty()) {
            result += words.front();
            words.pop_front();
            if (!words.empty()) {
                result.push_back(' ');
            }
        }
        return result;
    }
};

#endif /* StringSolution_hpp */
